package com.xfusion.chatglm.data.infrastructure.repository;

import com.xfusion.chatglm.data.domain.weixin.repository.IWeiXinRepository;
import com.xfusion.chatglm.data.infrastructure.redis.IRedisService;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 微信仓储服务
 */
@Slf4j
@Repository
public class WeiXinRepository implements IWeiXinRepository {
    private static final String key = "weixin_code";
    @Resource
    private IRedisService redisService;
    @Override
    public String genCode(String openId) {
        //获取值
        //当前缓存中有了，直接返回
        String isExitCode = redisService.getValue(key+"_"+openId);
        if (StringUtils.isNotBlank(isExitCode))return isExitCode;
        //生成值
        RLock lock = redisService.getLock(key);
        try{
            lock.lock(15, TimeUnit.SECONDS);
            String code = RandomStringUtils.randomNumeric(4);
            //防止重校验和重新生成
            //如果生成的验证码已经在redis中，则重新生成，最多生成10次
            for(int i = 0;i<10&& StringUtils.isNotBlank(redisService.getValue(key+"_"+code));i++){
                if (i<3){
                    code = RandomStringUtils.randomNumeric(4);
                } else if (i<5) {
                    code = RandomStringUtils.randomNumeric(5);
                } else if (i<9) {
                    code = RandomStringUtils.randomNumeric(6);
                    log.warn("验证码重复，生成6位字符串验证码,openId:{}  code:{}",openId,code);
                }else{
                    return "您的验证码获取失败，重新获取";
                }
            }
            //存储验证码
            redisService.setValue(key+"_"+code,openId,3*60*1000);
            redisService.setValue(key+"_"+openId,code);

            return code;
        }finally {
            lock.unlock();
        }
    }
}
